package com.CMS.server.domain;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = EntityTokens.PAGE_TABLE)
public class Page extends BaseEntity{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5308656273349298360L;

	@ManyToMany(fetch = FetchType.EAGER, cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
	@JoinTable
	(
		name = "PAGE_VERSION",
		joinColumns={@JoinColumn(name="ID_VERSION",referencedColumnName="ID")},
		inverseJoinColumns={@JoinColumn(name = "ID_PAGE",referencedColumnName="ID")}
	)
	protected List<PageVersion> versiones;
	
	@ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
	protected Language lang;
	
	@Column(name = EntityTokens.PAGE_EXTENSION, nullable = false)
	protected String extension;
	
	@Column(name = EntityTokens.PAGE_NOMBRE, nullable = false,unique=true)
	protected String name;
	
	@OneToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH},fetch = FetchType.EAGER, orphanRemoval = true)
	protected ItemMenu item;

	public Language getLang() {
		return lang;
	}

	public void setLang(Language lang) {
		this.lang = lang;
	}

	public String getExtension() {
		return extension;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<PageVersion> getVersiones() {
		return versiones;
	}

	public void setVersiones(List<PageVersion> versiones) {
		this.versiones = versiones;
	}
	
	public void setVersiones(PageVersion vesion){
		if(this.versiones == null)
			this.versiones = new ArrayList<PageVersion>();
		this.versiones.add(vesion);
	}

	public ItemMenu getItem() {
		return item;
	}

	public void setItem(ItemMenu item) {
		this.item = item;
	}
	
	public PageVersion getLastVersion(){
		PageVersion v = null;
		for(int i=0; i<versiones.size(); i++){
			if((v == null) || (v.getNroVersion() < versiones.get(i).nroVersion))
				v = versiones.get(i);
		}
		return v;
	}
}
